import { TASK_KEY_LABEL_MAP } from '../../../common/constants';
import errorCodesBuilder from '../../helpers/errorCodesBuilder';

const errorCodes = errorCodesBuilder('删除任务失败');

export default {
	name: 'TaskRemoveMany',
	description: '删除任务',
	type: 'RemoveManyTaskPayload',
	args: {
		filter: 'FilterRemoveManyTaskInput!',
	},
	async resolve({ args: { filter }, context: { request } }) {
		const {
			server: {
				methods: { removeTaskSession },
				app: {
					model: { Task, Job },
				},
			},
		} = request;

		if (filter._ids) {
			filter._id = { $in: [...filter._ids] };
			delete filter._ids;
		}

		let tasks;
		try {
			tasks = await Task.find(filter);
			tasks = tasks.filter(Boolean);
		} catch (err) {
			const error = errorCodes['[01]删除任务：查找任务mongo记录失败'].from(err);
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		try {
			await Promise.all(
				tasks.map(async task => {
					await (task.taskSessionId
						? removeTaskSession({
								taskSessionIds: [task.taskSessionId],
								jobId: task.jobId,
						  })
						: Promise.resolve());
					await task.remove();
					const job = await Job.findById(task.jobId);

					request.log.audit(
						{
							affects: [task.target],
							module: 'task',
							actionType: 'update',
							actionMessage: `更新${TASK_KEY_LABEL_MAP[task.taskType]}监测任务`,
							detail: `删除${
								TASK_KEY_LABEL_MAP[task.taskType]
							}监测任务队列中资产名称为${job?.note}的监测任务。`,
						},
						`[${task.target}]删除监测任务`
					);
				})
			);
		} catch (err) {
			const error = errorCodes['[01]删除任务：删除任务失败'].from(err);
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		return { numAffected: tasks.length };
	},
};
